from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from apps.user.serializers import UserLoginSerializer, UserSerializer, UserAvatarProfileSerializer
from apps.user.models import User
from apps.utils.authentication import TokenAuthentication
from apps.utils.responses import response_ok


class LoginView(APIView):
    authentication_classes = ()

    def post(self, request):
        serializer = UserLoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = serializer.login(code=serializer.validated_data.get('code'))
        return response_ok(data={'token': token}, message='登录成功')


class UserModelViewSets(ModelViewSet):

    authentication_classes = [TokenAuthentication, ]
    queryset = User.objects.all().order_by('-created_time')
    serializer_class = UserSerializer


class UserAvatarProfileView(APIView):

    authentication_classes = [TokenAuthentication, ]

    def post(self, request):
        ser = UserAvatarProfileSerializer(data=request.data, context={'request': request})
        ser.is_valid(raise_exception=True)
        ser.save()
        return response_ok(message="头像上传成功", data={})


class UserCurrentUserView(APIView):

    authentication_classes = [TokenAuthentication, ]

    def get(self, request):
        user = getattr(request, 'current_user', None)
        ser = UserSerializer(user)
        return response_ok(message='获取信息成功', data=ser.data)
